<?php

class Menu {

    private static $_controller;

    public static function getMenu($controller) {
        self::$_controller = $controller;
        $items = array(
//            array('label' => '<i class="icon-dashboard"></i> Dashboard', 'url' => array('/')),
            array('label' => '<i class="icon-male"></i> Clientes', 'url' => array('/productos/Cliente/admin'), 'access' => 'action_cliente_admin', 'active_rules' => array('module' => 'productos','controller' => 'cliente','noAction'=> self::$_controller->action->id =='remision'?'remision':NULL)),
            array('label' => '<i class="icon-building"></i> Ciudad', 'url' => array('/productos/Ciudad/admin'), 'access' => 'action_Ciudad_admin', 'active_rules' => array('module' => 'productos', 'controller' => 'ciudad')),
            array('label' => '<i class="icon-truck"></i> Proveedores', 'url' => array('/productos/Proveedor/admin'), 'access' => 'action_Proveedor_admin', 'active_rules' => array('module' => 'productos', 'controller' => 'proveedor','noAction'=> self::$_controller->action->id =='facturas'?'facturas':NULL)),
            array('label' => '<i class="icon-tags"></i> Categoria', 'url' => array('/productos/Categoria/admin'), 'access' => 'action_Categoria_admin', 'active_rules' => array('module' => 'productos', 'controller' => 'categoria')),
            array('label' => '<i class="icon-dropbox"></i> Bodega', 'url' => array('/productos/Bodega/admin'), 'access' => 'action_Bodega_admin', 'active_rules' => array('module' => 'productos', 'controller' => 'bodega')),
            array('label' => '<i class="icon-briefcase"></i> Productos', 'url' => array('/productos/Producto/admin'), 'access' => 'action_Producto_admin', 'active_rules' => array('module' => 'productos', 'controller' => 'producto','noAction'=> self::$_controller->action->id =='catalogo'?'catalogo':NULL)),
            
            array('label' => '<i class="icon-money"></i> Catalogo', 'url' => array('/productos/Producto/catalogo'), 'access' => 'action_Producto_catalogo', 'active_rules' => array('action' => 'catalogo')),
            
            
            array('label' => '<i class="icon-group"></i> Factura Proveedor', 'url' => array('/productos/Proveedor/facturas'), 'access' => 'action_Proveedor_facturas', 'active_rules' => array('action' => 'facturas')),
            
//            array('label' => '<i class="icon-tags"></i> Oportunidades', 'url' => array('/oportunidades/oportunidad/admin'), 'access' => 'action_oportunidad_admin', 'active_rules' => array('module' => 'oportunidades')),
            array('label' => '<i class="icon-file"></i> Guia Remision', 'url' => array('/productos/Cliente/remision'), 'access' => 'action_cliente_remision', 'active_rules' => array('action' => 'remision')),
//            array('label' => '<i class="icon-lightbulb"></i>Incidencia', 'url' => array('/incidencias/incidencia/admin'), 'access' => 'action_incidencia_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidencia')),
            array('label' => '<i class="icon-tasks"></i> Ordenes Requisicion', 'url' => array('/productos/OrdenRequisicion/admin'), 'access' => 'action_ordenRequisicion_admin', 'active_rules' => array('module' => 'productos','controller'=>'ordenRequisicion')),
            
        );

        return self::generateMenu($items);
    }

    public static function getAdminMenu($controller) {
        self::$_controller = $controller;
        $facturas= Factura::model()->count(array('condition' => 'estado = "PENDIENTE"'));
        
        $items = array(
            array('label' => '<i class="icon-mail-reply"></i>  Regresar ', 'url' => array('/')),
            array('label' => '<i class="icon-user"></i>  Usuarios', 'url' => Yii::app()->user->ui->userManagementAdminUrl, 'access' => 'Cruge.ui.*', 'active_rules' => array('module' => 'cruge')),
            array('label' => '<i class="icon-tasks"></i> Por Facturar <span class="badge badge-important">'.$facturas.'</span>', 'url' => array('/productos/factura/porFacturar'), 'access' => 'action_factura_porFacturar', 'active_rules' => array('action'=>'porFacturar'/*,'noAction'=> self::$_controller->action->id =='facturado'?'facturado':NULL*/)),
            array('label' => '<i class="icon-th"></i> Facturado', 'url' => array('/productos/factura/facturado'), 'access' => 'action_factura_facturado', 'active_rules' => array('action'=>'facturado'/*,'noAction'=> self::$_controller->action->id =='porFacturar'?'porFacturar':NULL*/)),
            array('label' => '<i class="icon-archive"></i> Facturas', 'url' => array('/productos/factura/admin'), 'access' => 'action_factura_admin', 'active_rules' => array( 'action' => 'admin')),
            array('label' => '<i class="icon-calendar"></i> Kardex', 'url' => array('/productos/Kardex/view'), 'access' => 'action_kardex_view', 'active_rules' => array('controller' => 'kardex')),
//            array('label' => '<i class="icon-book"></i>  Catálogos', 'url' => '#', 'items' => array(
//                    array('label' => 'Industrias', 'url' => array('/crm/industria/admin'), 'access' => 'action_industria_admin', 'active_rules' => array('module' => 'crm', 'controller' => 'industria')),
//                    array('label' => 'Etapas de Oportunidad', 'url' => array('/oportunidades/oportunidadEtapa/admin'), 'access' => 'action_oportunidadEtapa_admin', 'active_rules' => array('module' => 'oportunidades', 'controller' => 'oportunidadEtapa')),
//                    array('label' => 'Etapas de Cobranza', 'url' => array('/cobranzas/cobranzaEtapa/admin'), 'access' => 'action_cobranzaEtapa_admin', 'active_rules' => array('module' => 'cobranzas', 'controller' => 'cobranzaEtapa')),
//                    array('label' => 'Etapas de Tarea', 'url' => array('/tareas/tareaEtapa/admin'), 'access' => 'action_tareaEtapa_admin', 'active_rules' => array('module' => 'tareas', 'controller' => 'tareaEtapa')),
//                )),
//            array('label' => '<i class="icon-comments"></i>  Sms', 'url' => '#', 'items' => array(
//                    array('label' => 'Motivos', 'url' => array('/sms/smsMotivo/admin'), 'access' => 'action_smsMotivo_admin', 'active_rules' => array('module' => 'sms', 'controller' => 'smsMotivo')),
//                    array('label' => 'Plantillas', 'url' => array('/sms/smsPlantilla/admin'), 'access' => 'action_smsPlantilla_admin', 'active_rules' => array('module' => 'sms', 'controller' => 'smsPlantilla')),
//                )),
//            array('label' => '<i class="icon-lightbulb"></i>  Incidencias', 'url' => '#', 'items' => array(
//                    array('label' => 'Categoria', 'url' => array('/incidencias/incidenciaCategoria/admin'), 'access' => 'action_incidenciaCategoria_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaCategoria')),
//                    array('label' => 'Motivo', 'url' => array('/incidencias/incidenciaMotivo/admin'), 'access' => 'action_incidenciaMotivo_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaMotivo')),
//                    array('label' => 'Sub Motivo', 'url' => array('/incidencias/incidenciaSubmotivo/admin'), 'access' => 'action_incidenciaSubmotivo_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaSubmotivo')),
//                    array('label' => 'Via ingreso', 'url' => array('/incidencias/incidenciaViaIngreso/admin'), 'access' => 'action_incidenciaViaIngreso_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaViaIngreso')),
//                    array('label' => 'Estado', 'url' => array('/incidencias/incidenciaEstado/admin'), 'access' => 'action_incidenciaEstado_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaEstado')),
//                    array('label' => 'Prioridad', 'url' => array('/incidencias/incidenciaPrioridad/admin'), 'access' => 'action_incidenciaPrioridad_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaPrioridad')),
//                )),
//            array('label' => '<i class="icon-phone"></i>  Llamadas', 'url' => '#', 'items' => array(
//                    array('label' => 'Motivos', 'url' => array('/llamadas/llamadaMotivo/admin'), 'access' => 'action_llamadaMotivo_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaMotivo')),
//                    array('label' => 'Submotivos', 'url' => array('/llamadas/llamadaSubmotivo/admin'), 'access' => 'action_llamadaSubmotivo_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaSubmotivo')),
//                    array('label' => 'Subestados', 'url' => array('/llamadas/llamadaSubestado/admin'), 'access' => 'action_llamadaSubestado_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaSubestado')),
//                )),
//            array('label' => '<i class="icon-folder-open"></i>  Historiales', 'url' => '#', 'items' => array(
//                    array('label' => 'Llamadas Entrantes', 'url' => array('/llamadas/llamada/historialEntrantes'), 'access' => 'action_llamada_historialEntrantes', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamada', 'action' => 'historialEntrantes')),
//                    array('label' => 'Llamadas Salientes', 'url' => array('/llamadas/llamada/historialSalientes'), 'access' => 'action_llamada_historialSalientes', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamada', 'action' => 'historialSalientes')),
//                    array('label' => 'Sms', 'url' => array('/sms/sms/historial'), 'access' => 'action_sms_historial', 'active_rules' => array('module' => 'sms', 'controller' => 'sms')),
//                    array('label' => 'Emails', 'url' => array('/mail/mail/historial'), 'access' => 'action_mail_historial', 'active_rules' => array('module' => 'mail', 'controller' => 'mail')),
//                )),
        );

        return self::generateMenu($items);
    }

    /**
     * Function to create a menu with acces rules and active item
     * @param array $items items to build the menu
     * @return array the formated menu
     */
    private static function generateMenu($items) {
        $menu = array();

        foreach ($items as $k => $item) {
            $access = false;
            $menu_item = $item;

            // Check children access
            if (isset($item['items'])) {
                $menu_item['items'] = array();
                // Check childrens access
                foreach ($item['items'] as $j => $children) {
                    if ($access = Yii::app()->user->checkAccess($children['access'])) {
                        $menu_item['items'][$j] = $children;
                        if (isset($children['active_rules']) && self::getActive($children['active_rules'])) {
                            $menu_item['items'][$j]['active'] = true;
                            $menu_item['active'] = true;
                        }
                    }
                }
            } else {
                // Check item access
                if (isset($item['access'])) {
                    $access = Yii::app()->user->checkAccess($item['access']);
                } else {
                    $access = true;
                }
                // Check active
                if (isset($item['active_rules'])) {
                    $menu_item['active'] = self::getActive($item['active_rules']);
                }
            }

            // If acces to the item or any child add to the menu
            if ($access) {
                $menu[] = $menu_item;
            }
        }

        return $menu;
    }

    /**
     * Function to compare the menu active rules with the current url
     * @param array $active_rules the array of rules to compare
     * @return boolean true if the rules match the current url
     */
    private static function getActive($active_rules) {
        $current = false;
        if (self::$_controller) {
            if (is_array(current($active_rules))) {
                foreach ($active_rules as $rule) {
                    $operator = isset($rule['operator']) ? $rule['operator'] : '==';
                    
                    if (isset($rule['module']) && self::$_controller->module) {
                        if ($operator == "==")
                            $current = self::$_controller->module->id == $rule['module'];
                        if ($operator == "!=")
                            $current = self::$_controller->module->id != $rule['module'];
                    }
                    if (isset($rule['controller'])) {
                        if ($operator == "==")
                            $current = self::$_controller->id == $rule['controller'];
                        if ($operator == "!=")
                            $current = self::$_controller->id != $rule['controller'];
                    }
                    if (isset($rule['action'])) {
                        if ($operator == "==")
                            $current = self::$_controller->action->id == $rule['action'];
                        if ($operator == "!=")
                            $current = self::$_controller->action->id != $rule['action'];
                    }
                    if (!$current)
                        break;
                }
            } else {
                $operator = isset($active_rules['operator']) ? $active_rules['operator'] : '==';

                if (isset($active_rules['module']) && self::$_controller->module) {
                    if ($operator == "==")
                        $current = self::$_controller->module->id == $active_rules['module'];
                    if ($operator == "!=")
                        $current = self::$_controller->module->id != $active_rules['module'];
                }
                if (isset($active_rules['controller'])) {
                    if ($operator == "==")
                        $current = self::$_controller->id == $active_rules['controller'];
                    if ($operator == "!=")
                        $current = self::$_controller->id != $active_rules['controller'];
                }
                if (isset($active_rules['action'])) {
                    if ($operator == "==")
                        $current = self::$_controller->action->id == $active_rules['action'];
                    if ($operator == "!=")
                        $current = self::$_controller->action->id != $active_rules['action'];
                }
                if (isset($active_rules['noAction'])) {
                        if ($operator == "==")
                            $current = self::$_controller->action->id != $active_rules['noAction'];
                        if ($operator == "!=")
                            $current = self::$_controller->action->id == $active_rules['noAction'];
                    }
            }
        }
        return $current;
    }

}
